#include "kservice/display.h"
#include "ff.h"

int draw_bitmap(Display d, const char *name, int x, int y)
{
    FIL file;
    FRESULT rs = f_open(&file, name, FA_READ);
    if (FR_OK != rs)
    {
        return 0;
    }

    UINT br;
    static unsigned buff[802];

    unsigned h, w, color, round;
    unsigned char r, g, b;
    f_read(&file, buff, 200, &br);
    int *q = (int *)((void*)buff + 18); // skip over 14 bytes file header
    // q++;                      // skip 4 bytes in image header
    w = *q;                   // width in pixels
    h = *(q + 1);             // height in pixels

    round = 4 * ((3 * w + 3) / 4);
    int tail = 54 ;
    f_lseek(&file, tail);

    for (int i = y + h -1; i >=0; i--)
    {
        const char *ptr = (const char *)buff;
        br = 0;
        f_read(&file, buff, round, &br);
        for (int j = x; j < x + w; j++)
        {
            b = *ptr;
            g = *(ptr + 1);
            r = *(ptr + 2);
            color = (b << 16) | (g << 8) | r;

            d->buff[j + i * d->twidth] = color;
            ptr += 3;
        }
        tail += round;
        f_lseek(&file, tail);
    }
    return 0;
}